$(function () {
    let pageParams = {
        page: 0,
        limit: 12,
        hasMore: true,
    }
    renderProd().then((prodData) => {
        renderBanner(prodData).then(() => {
            pageToRender(prodData)
            lazyLoad()
        })

    }).catch(err => {
        console.log("Pormise Error...", err);
    })
    function renderProd () {
        return new Promise((resolve, reject) => {
            let { page, limit } = pageParams
            $.ajax({
                url: `/api/getProduct?page=${page}&limit=${limit}`,
                type: 'get',
                success: res => {
                    if (res.code == 200) {
                        res.result = res.result || []
                        //renderProdResult(res.result)
                        if (res.result.length == 0) {
                            pageParams.hasMore = false
                        }
                        resolve(res.result)
                    } else {
                        reject()
                    }
                    changeLoadStatus(false)
                }
            })
        })
    }
    function renderProdResult (paramsData) {
        if (paramsData.length / pageNum > 1) {
            $('#pagination').pagination({
                pages: Math.ceil(paramsData.length / pageNum), //总页数
                edges: 2,
                cssStyle: 'pagination-sm', //按纽大小pagination-lg或写入自定义css
                displayedPages: 3, //显示几个
                onPageClick: function (page, event) {
                    //点击时调用
                    let copyData = JSON.parse(JSON.stringify(paramsData))
                    let data = copyData.splice((page - 1) * pageNum, pageNum)
                    pageToRender(data)
                },
                onInit: function (page) {
                    //刷新时或初始化调用
                    let copyData = JSON.parse(JSON.stringify(paramsData))
                    let data = copyData.splice((page - 1) * pageNum, pageNum)
                    pageToRender(data)
                }
            });
        } else {
            pageToRender(paramsData)
        }
    }
    function pageToRender (data) {
        let dom = ``
        data.forEach(item => {
            dom += `
            <div class="card" data-id="${item.id}">
                <header class="card__thumb">
                    <a href="javascript:void(0)"><img src="${item.imgSrc}" style="width:100%" /></a>
                </header>
                <div class="card__body">
                    <h2 class="card__title"><a href="javascript:void(0)">${item.title}</a></h2>
                    <div class="card__subtitle">${item.desc}</div>
                    <p class="card__description">
                        <img src="${item.qrSrc}" style="width:100%" />
                        </p>
                </div>
            </div>
        `
        })
        $(".card_box").append(dom)
        cardHover()

    }
    function renderBanner (prodData) {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: 'get',
                url: "/api/getBanner",
                success: function (res) {
                    res.result = res.result || []
                    renderBannerResult(res.result, prodData, resolve)
                    
                }
            })
        })
    }
    function renderBannerResult (paramsData, prodData, resolve) {
        let dom = ``
        let olDom = ``
        let olIndex = 0
        let bannerArr = []
        paramsData.forEach((item, index) => {
            let idArr = prodData.filter(v => { if (v.id == item.prodId) { return v } })[0]
            let src = ""
            let title = ""
            if (idArr) {
                src = idArr.imgSrc
                title = idArr.title
                bannerArr.push(item.src)
                dom += `
                    <a class="carousel-item "  data-id="${item.prodId}">
                        <img src="${item.src}" class="d-block w-100 banner_img_index" alt="${item.title}"  />
                    </a>
                `;
                if ($tool.IsPC()) {
                    olDom += `
                        <div  class="abbrImg">
                            <img data-target="#carouselExampleIndicators" data-slide-to="${olIndex++}"
                            src="${src}" alt="" />
                            <span class="title">${title}</span>    
                        </div>
                        `
                } else {
                    olDom += `
                        <li data-target="#carouselExampleIndicators" data-slide-to="${olIndex++}" style="box-shadow:unset !important"></li>
                        `
                }
            }
        })

        let redius = document.createElement("img")
        redius.src = bannerArr[0]
        //redius.classList = "d-block w-100 banner_img_index active"
        //第一张banner加载完成后再添加active 先渲染首屏
        redius.onload = function (res) {
            //第一张banner加载完成开始加载产品
            resolve()
            //第一张banner加载完成才开始加载其他banner
            $(".carousel-inner").html(dom)
            $(".carousel-indicators").html(olDom)

            let $firstAbbr = $(".abbrImg").eq(0)
            let $firstBanner = $(".carousel-item").eq(0)
            $firstBanner.addClass("active")
            
            //第一张abbrImg加载完成后再添加active
            $firstAbbr.children("img").on('load', function (res) {
                $firstAbbr.addClass("active")
            })
            /* //ol加载完成回调
            let details_img = $(".abbrImg").children("img");    //所有的图片
            let img_len = details_img.length;
            details_img.on('load', function (res) {
                if (!--img_len) {
                    //ol加载完成才开始加载产品
                }
            }); */
            $(".carousel-item").click(function () {
                //取消hover监听
                $(".card_box").find(".card").unbind()
                //滚动条滚动，增加active
                let fId = $(this).data("id")
                let fDom = $(`.card_box .card[data-id="${fId}"]`)
                let scrollTopH = fDom[0].getBoundingClientRect().top
                console.log("scrollTopH", scrollTopH);
                $("html").animate({ scrollTop: scrollTopH - 100 }, 300, "swing", function () {
                    fDom.siblings().removeClass("card__active")
                    fDom.addClass("card__active")
                    $(".card_box").find(".card").hover(hoverInEvents, hoverOutEvents)
                })
    
    
                //两秒后，恢复hover监听
                /* let timer = setTimeout(() =>{
                    $(".card_box").find(".card").hover(hoverInEvents, hoverOutEvents)
                    clearTimeout(timer)
                },2000) */
            })
        }
    }
    function cardHover () {
        $(".card_box").find(".card").hover(hoverInEvents, hoverOutEvents)
    }
    function hoverInEvents () {
        $(this).addClass("card__active")

    }
    function hoverOutEvents () {
        $(this).removeClass("card__active")
    }

    function lazyLoad () {
        $(".lazy_load").click(function () {
            if (!pageParams.hasMore) { return }
            pageParams.page++
            changeLoadStatus(true)
            renderProd().then((prodData) => {
                pageToRender(prodData)
            })

        })
        $(".lazy_load").hover(function () {
            $(this).css("background-color", "#825AA5")
            $(this).css("color", "#fff")
        }, function () {
            $(this).css("background-color", "#F8F7FC")
            $(this).css("color", "#825AA5")

        })
    }
    function changeLoadStatus (flag) {
        let $lazy = $(".lazy_load")
        let $tips = $lazy.children(".sp-tips")
        let $wave = $lazy.children(".sp-wave")
        if (!pageParams.hasMore) {
            $tips.css("display", "inline-block")
            $wave.css("display", "none")
            $tips.text("没有更多啦~")
            return
        }
        if (flag) {
            $tips.css("display", "none")
            $wave.css("display", "inline-block")
        } else {
            $tips.css("display", "inline-block")
            $wave.css("display", "none")
        }
    }
})
